package com.pishou.shop;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.pishou.URLConfig;
import com.pishou.code.bean.Cart;
import com.pishou.code.util.VideoPlayList;
import com.pishou.player.R;
import com.pishou.code.bean.Product;
import com.pishou.Data;
import com.pishou.player.TextureActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {

    private String[] categorys;
    private List<Product> checked_products;
    private GridView gd_goods;
    private String checked_category;
    private static List<Product> products;

    private float mPosX;
    private float mCurrentPosX;
    private boolean left_move_action = false;

    private Timer timer;
    private TimerTask task;

    private boolean dispatcherFlag = true;

    private ScrollView sv_cart;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Data.comment_ad_action){
            Intent intent = new Intent(getApplicationContext(),DetailActivity.class);
            intent.putExtra("sku", VideoPlayList.getCurrentVideo().getSku());
            Data.comment_ad_action = false;
            startActivity(intent);
        }

        // 获取数据，设置初始标志
        products = Data.products;
        categorys = Data.categorys;
        checked_products = products;
        checked_category = categorys[0];

        // 构建分类选择列表
        ListView lv_category = (ListView)findViewById(R.id.lv_category);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.category_item,categorys);
        lv_category.setAdapter(adapter);
        lv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String category = categorys[position];
                if (!category.equals(checked_category)){
                    checked_products = new ArrayList<>();
                    for (Product product:products){
                        if (category.equals(product.getCategory()) || category.equals(categorys[0])){
                            checked_products.add(product);
                        }
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            gd_goods.setAdapter(new MyGoodsAdapt());
                        }
                    });
                    checked_category = category;
                }
            }
        });

        // 构建全部商品列表
        gd_goods = (GridView)findViewById(R.id.gd_goods);
        gd_goods.setAdapter(new MyGoodsAdapt());
        gd_goods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent intent = new Intent(getApplicationContext(),DetailActivity.class);
                intent.putExtra("sku",checked_products.get(position).getSku());
                startActivity(intent);
            }
        });
        gd_goods.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
                boolean flag = Data.addCart(checked_products.get(position));
                if (!flag){
                    sv_cart.fullScroll(ScrollView.FOCUS_DOWN);
                }
                initCart();
                return true;
            }
        });
        // 实例化购物车
        initCart();

        // 构建底部图片
        ImageView bottomImage = (ImageView) findViewById(R.id.iv_bottomImage);
        setImage(bottomImage, URLConfig.oss_host + "eshop/slide-1.jpg",false,null,null);

        sv_cart = findViewById(R.id.sv_cart);
    }

    @Override
    protected void onPause() {
        dispatcherFlag = false;
        if (timer!=null){
            timer.cancel();
            timer = null;
        }
        if (task!=null){
            task.cancel();
            task = null;
        }
        super.onPause();
    }

    @Override
    protected void onStart() {
        dispatcherFlag = true;
        timer = new Timer();
        task = new TimerTask(){
            @Override
            public void run() {
                // 跳转到播放广告页面，设置该Activity为第一个页面，清空它上面的栈
                Intent intent= new Intent(getApplicationContext(), TextureActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        };
        if (timer!=null && task!=null){
            timer.schedule(task,15*1000l);
        }
        initCart();
        super.onStart();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN && dispatcherFlag){
            timer.cancel();
            task.cancel();
            timer = null;
            task = null;
            timer = new Timer();
            task = new TimerTask(){
                @Override
                public void run() {
                    Intent intent= new Intent(getApplicationContext(), TextureActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            };
            if (timer!=null && task!=null){
                timer.schedule(task,15*1000l);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void pay(View v){
        Intent intent = new Intent(this,PayActivity.class);
        startActivity(intent);
    }

    private void initCart(){
        LinearLayout ll_cart = (LinearLayout) findViewById(R.id.ll_cart);
        ll_cart.removeAllViews();
        for (Cart cart:Data.carts){
            View view = View.inflate(getApplicationContext(),R.layout.cart_item,null);
            ImageView image = (ImageView)view.findViewById(R.id.cart_image);
            setImage(image, URLConfig.oss_host + "image/" + cart.getProduct().getSku()+".jpg",true,null,200);
            image.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            mPosX = event.getX();
                            left_move_action = true;
                            break;
                        case MotionEvent.ACTION_MOVE:
                            mCurrentPosX = event.getX();
                            if (mPosX - mCurrentPosX  > 100 && left_move_action){
                                left_move_action = false;
                                // 购物车减1
                                int index = ((ViewGroup)view.getParent().getParent()).indexOfChild((View)view.getParent());
                                Data.reduceCart(index);
                                initCart();
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            break;
                        default:
                            break;
                    }
                    return true;
                }
            });
            TextView quantity = (TextView) view.findViewById(R.id.cart_quantity);
            quantity.setText(cart.getQuantity().toString());
            ll_cart.addView(view);
        }
        TextView tv_cart_js = (TextView) findViewById(R.id.tv_cart_js);
        tv_cart_js.setText("¥ " + Data.cartTotal +"\n结算");
        if (Data.cartTotal>0){
            tv_cart_js.setClickable(true);
            tv_cart_js.setBackgroundColor(getResources().getColor(R.color.enable));
        }else{
            tv_cart_js.setClickable(false);
            tv_cart_js.setBackgroundColor(getResources().getColor(R.color.black_overlay));
        }
    }

    private  class MyGoodsAdapt extends BaseAdapter{
        @Override
        public int getCount() {
            return checked_products.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (convertView==null){
                view = View.inflate(getApplicationContext(),R.layout.goods_item,null);
            }else{
                view = convertView;
            }
            TextView tv_name = view.findViewById(R.id.tv_name);
            ImageView iv_goodsImage = view.findViewById(R.id.iv_goodsImage);
            TextView tv_price = view.findViewById(R.id.tv_price);
            tv_name.setText(checked_products.get(position).getName());
            tv_price.setText("¥ "+checked_products.get(position).getPrice());
            setImage(iv_goodsImage, URLConfig.oss_host + "image/"+checked_products.get(position).getSku()+".jpg",true,null,200);
            return  view;
        }
    }

    /**
     * 设置图片
     * @param iv
     * @param path
     */
    private synchronized void setImage(final ImageView iv,  final String path, final Boolean scal_flag, final Integer width, final Integer height) {
        new Thread(){
            @Override
            public void run() {
                File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(),Base64.DEFAULT));
                if (!file.exists()){
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        int code = conn.getResponseCode();
                        if (code == 200){
                            InputStream in = conn.getInputStream();
                            int len = -1;
                            byte[] buffer = new byte[1024];
                            FileOutputStream fos = new FileOutputStream(file);
                            while ((len = in.read(buffer))!=-1) {
                                fos.write(buffer, 0, len);
                            }
                            fos.close();
                            in.close();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (iv!=null){
                    if (scal_flag){
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(file.getAbsolutePath(),options);
                        int w = options.outWidth;
                        int h = options.outHeight;
                        // 计算缩放比
                        int scalX = 0;
                        if ( width != null && width != 0){
                            scalX = w/width;
                        }
                        int scalY = h/height;
                        int scal = 1;
                        // 计算宽和高的缩放比，选择缩放比较大的使用
                        if (scalX>scalY && scalX>scal) {
                            scal = scalX;
                        }
                        if (scalY > scalX && scalY > scal) {
                            scal = scalY;
                        }
                        options.inSampleSize = scal;
                        // 取消不读取图片的设置，并且携带缩放比读取图片
                        options.inJustDecodeBounds = false;
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }else{
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }
                }
                super.run();
            }
        }.start();
    }
}
